<template>
  <view class="app-content" @touchstart="onTouchstart" @touchend="onTouchend">
    <!-- 导航栏 -->
    <uni-nav-bar ref="navBar" status-bar="true" left-icon="back" background-color="#253155" color="white" :shadow="false" :right-margin="capsuleLeft" :title="title" @clickLeft="uni.navigateBack()" />
    <render :component-list="componentList" :device-id="deviceId" />
  </view>
</template>

<script>
import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue'
import {
  mapState
} from 'vuex'
const LAST_CACHE_KEY = 'CA_CONTROLLER_'
const LOADING = '加载中.'

export default {
  components: { uniNavBar },
  data() {
    return {
      uni,
      statusBarHeight: this.$api.config.sysInfo.statusBarHeight,
      // #ifdef MP
      capsuleLeft: this.$api.config.sysInfo.screenWidth - this.$api.config.capsule.left,
      // #endif
      // #ifndef MP
      capsuleLeft: 0,
      // #endif
      controllerId: undefined,
      controllerList: [],
      componentList: [],
      title: 'Loading',
      deviceId: undefined,
      productId: undefined,
      current: 0,
      startX: 0
    }
  },
  onLoad(options) {
    // 设备ID
    this.deviceId = options.did
    // 产品ID
    this.productId = options.pid
    // 获取遥控器列表 & 加载默认遥控器
    this.init()
    // 获取设备数据点
    this.loadDeviceData()
  },
  onUnload() {
    uni.sendSocketMessage({
      data: JSON.stringify({
        code: 1,
        deviceId: 0
      }),
      success(res) {
        console.log('关闭设备遥控器')
      }
    })
  },
  computed: {
    ...mapState(['deviceDatas'])
  },
  methods: {
    init() {
      const that = this
      uni.showLoading({
        title: LOADING
      })
      that.$api.request('controller', 'list', {
        productId: that.productId
      }, failres => {
        uni.hideLoading()
        that.$api.msg(failres.errmsg)
      }).then(res => {
        if (res.data.length > 0) {
          const lastRaw = uni.getStorageSync(LAST_CACHE_KEY + that.deviceId)
          let index = 0
          if (lastRaw) {
            // 优先使用上次的
            for (let i = 0; i < res.data.length; i++) {
              if (parseInt(lastRaw) === res.data[i].id) {
                index = i
                break
              }
            }
          }
          that.current = index
          that.title = res.data[index].title
          // 加载组件列表
          that.controllerList = res.data
          that.loadComponents(index)
        }
        uni.hideLoading()
      })
    },
    loadDeviceData() {
      const o = {
        code: 1,
        deviceId: this.deviceId
      }
      console.log(JSON.stringify(o))
      uni.sendSocketMessage({
        data: JSON.stringify(o),
        success(res) {
          console.log('打开设备遥控器')
        }
      })
    },
    loadComponents(index) {
      const that = this
      uni.showLoading({
        title: LOADING
      })
      that.$api.request('controller', 'listComponent', {
        controllerId: that.controllerList[index].id
      }, failres => {
        uni.hideLoading()
        that.$api.msg(failres.errmsg)
      }).then(res => {
        // 将component attr 转换为Map结构，方便使用
        res.data.forEach(item => {
          const attrObj = {}
          item.attrList.forEach(sitem => {
            attrObj[sitem.idTag] = sitem
            if (sitem.type === 1) {
              // 数字
              if (sitem && sitem.value) {
                attrObj[sitem.idTag + 'V'] = parseInt(sitem.value)
              }
            } else if (sitem.type === 2) {
              if (sitem && sitem.value) {
                attrObj[sitem.idTag + 'V'] = sitem.value
              } else {
                attrObj[sitem.idTag + 'V'] = ''
              }
            } else if (sitem.type === 3) {
              if (sitem && sitem.value) {
                attrObj[sitem.idTag + 'V'] = parseFloat(sitem.value)
              }
            } else if (sitem.type === 4) {
              if (sitem && sitem.value) {
                attrObj[sitem.idTag + 'V'] = (sitem.value === 'true')
              }
            } else if (sitem.type === 5) {
              if (sitem && sitem.value) {
                attrObj[sitem.idTag + 'V'] = sitem.value
              } else {
                attrObj[sitem.idTag + 'V'] = ''
              }
            } else if (sitem.type === 6) {
              console.log('发现数据点属性')
              console.log(sitem)
              console.log(that.deviceDatas)
              // 组件属性，为绑定数据点
              if (sitem && sitem.value) {
                // stiem.value 为数据点的名字
                attrObj[sitem.idTag + 'V'] = sitem.value
              } else {
                attrObj[sitem.idTag + 'V'] = ''
              }
            }
          })
          item.attr = attrObj
        })
        console.log('componentList')
        this.componentList = res.data
      })
    },
    // 发送一条命令， cmd: 具体命令字符 obj: 附加对象,例如滑动条等,可能需要附加当前进度信息
    sendCmd(cmd, obj = {}) {
      const that = this
      if (cmd) {
        that.$api.request('device', 'sendCmd', {
          deviceId: that.deviceId,
          cmd: cmd,
          param: JSON.stringify(obj)
        }).then(res => {

        })
      }
    },
    controllerChange() {
      const that = this
      uni.setStorage({
        key: LAST_CACHE_KEY + that.deviceId,
        data: that.controllerList[this.current].id
      })
      that.title = that.controllerList[this.current].title
      that.loadComponents(this.current)
    },
    navBack() {
      uni.navigateBack()
    },
    onTouchstart(e) {
      this.startX = e.changedTouches[0].pageX
    },
    onTouchend(e) {
      if (e.changedTouches[0].pageX - this.startX > uni.upx2px(330)) {
        // 加1
        if (this.current < this.controllerList.length - 1) {
          this.current = this.current + 1
          this.controllerChange()
        }
      } else if (this.startX - e.changedTouches[0].pageX > uni.upx2px(330)) {
        // 减1
        if (this.current > 0) {
          this.current = this.current - 1
          this.controllerChange()
        }
      }
    }
  }
}
</script>

<style>

</style>
